package cn.edu.ncut.cs.springboot.petmanagementsystem.service.Impl;

import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.PetCareRecordMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.PetCareService;
import cn.edu.ncut.cs.springboot.petmanagementsystem.vo.PetCareRecordV0;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
public class PetCareServiceImpl implements PetCareService {

    @Autowired
    private PetCareRecordMapper petCareRecordMapper;

    @Override
    public Page<PetCareRecordV0> getPageByPetId(Integer pageNum, Integer pageSize, Long petId) {
        Page<PetCareRecordV0> page = new Page<>(pageNum, pageSize);
        return (Page<PetCareRecordV0>) petCareRecordMapper.selectCareRecordPage(page, petId);
    }

    @Override
    public PetCareRecord getCareRecordById(Long id) {
        if (id == null) {
            return null;
        }
        return petCareRecordMapper.selectById(id);
    }

    @Override
    public PetCareRecordV0 getCareRecordDetailById(Long id) {
        if (id == null) {
            return null;
        }
        return petCareRecordMapper.selectCareRecordById(id);
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean createCareRecord(PetCareRecord record) {
        if (record == null || record.getPetId() == null) {
            throw new IllegalArgumentException("宠物ID不能为空");
        }

        // 查询当前最大ID
        LambdaQueryWrapper<PetCareRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(PetCareRecord::getId).last("LIMIT 1");
        PetCareRecord maxRecord = petCareRecordMapper.selectOne(wrapper);
        
        // 设置新ID为最大ID+1
        Long newId = (maxRecord != null && maxRecord.getId() != null) ? maxRecord.getId() + 1 : 1L;
        record.setId(newId);
        
        int result = petCareRecordMapper.insert(record);
        return result > 0;
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean updateCareRecord(PetCareRecord record) {
        if (record == null || record.getId() == null) {
            return false;
        }

        record.setUpdateTime(LocalDateTime.now());
        int result = petCareRecordMapper.updateById(record);
        return result > 0;
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean deleteCareRecord(Long id) {
        if (id == null) {
            return false;
        }
        int result = petCareRecordMapper.deleteById(id);
        return result > 0;
    }
}
